package com.tuling.mybaitis_spring.aspect;

import com.tuling.mybaitis_spring.aspect.advice.AopBeforeMethodAdvice;
import com.tuling.mybaitis_spring.aspect.advice.AopBeforeMethodAdvice2;
import com.tuling.mybaitis_spring.service.UserService;
import org.aopalliance.aop.Advice;
import org.springframework.aop.*;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.aop.support.StaticMethodMatcherPointcut;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

import java.lang.reflect.Method;
@EnableAspectJAutoProxy
public class AdviceTest {
	public static void main(String[] args) {

//		UserService target = new UserService();
		ProxyFactory proxyFactory = new ProxyFactory();
//		proxyFactory.setTarget(target);
		proxyFactory.addInterface(UserInterface.class);
		//在执行addAdvice 的时候会将advice 封装成advisor
		proxyFactory.addAdvice(new AopBeforeMethodAdvice());
		proxyFactory.addAdvice(new AopBeforeMethodAdvice2());
		proxyFactory.addAdvice(new AfterReturningAdvice() {
			@Override
			public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
				System.out.println("---after------");
			}
		});

		//将两个bean 原始对象的bean 与 切面逻辑的bean 绑定关系
		BeanNameAutoProxyCreator beanNameAutoProxyCreator = new BeanNameAutoProxyCreator();
		beanNameAutoProxyCreator.setBeanNames("原始对象的beanName");
		beanNameAutoProxyCreator.setInterceptorNames("切面逻辑的beanName");
//		proxyFactory.addAdvisor(new PointcutAdvisor() {
//			@Override
//			public Pointcut getPointcut() {
//				return new StaticMethodMatcherPointcut() {
//					@Override
//					public boolean matches(Method method, Class<?> targetClass) {
//						return method.getName().equals("selectUser");
//					}
//				};
//			}
//
//			@Override
//			public Advice getAdvice() {
//				return new AopBeforeMethodAdvice();
//			}
//
//			@Override
//			public boolean isPerInstance() {
//				return false;
//			}
//		});
		UserInterface userService = (UserInterface)proxyFactory.getProxy();
		userService.selectUser("xioa");
	}
}
